// pages/promise/promise.js
const http = require("../../utils/request");
const utils = require("../../utils/util");
const searchList = ['companyName', 'contacts', 'phone', 'address']
const feedback = require("../../utils/feedback")

// const config = import("./config");
let app = getApp();
Page({
  properties: {
  },
  data: {
    title: "农场信息",
    value: "",
    isdelete: false,
    // isSelected: false,
    isLoading: true,
    comfirmingDeletion: false,
    //骨架
    animationList: [{
      title: '渐变加载效果',
      value: 'gradient',
      loading: true,
    }],
    // 搜索框
    searchPlaceholder: "搜索公司、联系人、电话、地址",
    // 公司卡片
    companyInfo: null,
    // 提示框
    dialogTitle: "对话框标题",
    dialogContent: "告知当前状态、信息和解决方法，等内容。描述文案尽可能控制在三行内",
    showConfirm: false
  },

  /**
   * @public
   */
  tapComfirmDeleteOrDelete() {
    if (this.data.isdelete) {
      //确认删除
      wx.showModal({
        title: '是否确认删除',
        content: '本操作将删除公司及其相关数据',
        complete: (res) => {
          if (res.confirm) {
            this.setData({
              comfirmingDeletion: true,
            })
            //子组件传递数据
            this.changeDeleteState()
            this.deleteCompany(this.data.companyInfo)
            this.setData({
              comfirmingDeletion: false,
            })
          }
        }
      })
    } else {  //页面进入删除状态
      this.setData({
        isdelete: !this.data.isdelete,
        // isSelected: false
      })
    }
  },
  /**
   * @private
   * @param {String} childName 子组件名
   */
  getChildComponentData(childName) {
    console.log(this.selectAllComponents(childName).map((AComponent) => AComponent.data))
    return this.selectAllComponents(childName).map((AComponent) => AComponent.data);
  },
  /**
   * 请求函数
   * @param {Array} companyInfo 
   */
  deleteCompany(companyInfo) {
    //TODO：删除公司接口
    let deleteIdsList = this.getdeletedCompaniesList(companyInfo)
    feedback.showISee('删除公司' + deleteIdsList)
  },
  /**
   * 
   * @param {Array} companyInfo 
   * @returns {Array<Int>} 需要删除公司的ids
   */
  getdeletedCompaniesList(companyInfo) {
    return companyInfo.filter((aCompanyInfo) =>
      aCompanyInfo.isSelected == true
    ).map((aCompanyInfo) =>
      aCompanyInfo.id
    )
  },
  /**
   * @private
   * @param {int} id 公司的id，新增公司id=-1
   */
  gotoConpanyDetail(id) {
    wx: wx.navigateTo({
      url: `/pages/companyInformation/companyDetails/companyDetails?id=` + id,
      events: false,
      success: (result) => { },
      fail: (res) => { },
      complete: (res) => { },
    })
  },
  /**
   * @private
   */
  changeDeleteState() {
    this.setData({
      isdelete: !this.data.isdelete,
    })
  },
  /**
   * @private
   * @param {function || 空} success 
   */
  getAllCompanyInfo(success) {
    const getPage = 1;  //分页请求页数
    const getSize = 100;
    http.getRequest(
      // TODO:暂定用分页查询代替查询全部,数据量多后可能出现获取的公司不足
      "/admin/company/" + getPage + "/" + getSize,
      {},
      (res) => {
        success && success()
        this.setData({
          companyInfo: res.data.data.records
        })
      },
      (err) => {
        wx.showModal({
          title: '加载失败',
          content: err.message || "获取数据失败" + "请稍后重试",
          showCancel: false,
          complete: (res) => {
            wx.navigateBack(2)
          }
        })
      }
    )
  },
  /**
   * @public
   * @description 设置card是否展示，通过匹配搜索框里的字符串，判断companyInfo[index].isDisable
   */
  searchValueChange: utils.debounce(function (e) {
    const searchBoxValue = e.detail.value
    this.setData({
      companyInfo: this.updateCompanyInfoDisable(this.data.companyInfo, searchList, searchBoxValue)
    })
  }),
  clearSearchValue(){
    this.setData({
      value:'',
      companyInfo: this.updateCompanyInfoDisable(this.data.companyInfo)
    })
  },
 /**  
 * @description 筛选companyInfo含有searchValue的公司信息;如果searchValue或searchKeysList没有被传参则展示所有companyInfo  
 * @param {Array<Object>} companyInfo 公司信息数组  
 * @param {Array<String>} [searchKeysList] 搜索的companyInfo的keyList，可选  
 * @param {String} [searchValue] 输入框中的值，可选  
 * @returns {Array<Object>} 筛选后的companyInfo  
 */
  updateCompanyInfoDisable(companyInfo, searchKeysList, searchValue) {
    return companyInfo.map((element) => {
      const isDisable = searchValue&&searchKeysList&&(!searchKeysList.some((key) => element[key] && element[key].match(searchValue)))
      return { ...element, isDisable }
    })
  },

  /**
   * @public 获取公司卡片的data
   */
  getCardsData(data) {
    this.setData({
      companyInfo: data.detail
    })
  },

  /**
   * 添加公司信息按钮
   */
  gotoAddConpany() {
    if (this.data.isdelete) {
      this.changeDeleteState()
    }
    else {
      this.gotoConpanyDetail(-1)
    }
  },



  /**
   * icon
   */
  onIconTap(event) {
    console.log(event)
  },

  /**
   * 对话框
   */
  async showDialog(title, content) {
    this.setData({
      showConfirm: true,
      dialogTitle: title,
      dialogContent: content
    })
  },
  confirmDialog() {
    this.closeDialog()
  },
  closeDialog() {
    this.setData({
      showConfirm: false,
      dialogTitle: '',
      dialogContent: ''
    });
  },

  /*
  *通用函数 
  */
  getIdFromTagId(result) {
    return result.match(/\d+$/)[0]
  },

  onShow() {
    this.getAllCompanyInfo()
  },
  onLoad() {
    this.getAllCompanyInfo(() => {
      this.setData({
        isLoading: false
      })
    })
  },
})

